<?php 
namespace BLL\DAO;

use BLL\DataModel as DM;
use Exception;
/*
 *  
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * 
 * Copyright 2015 Max Group. All rights reserved.
 * 
 */

/**
 * Description of TableHelper
 *
 * @author david
 */
class ModelBuilder {

    private static $template;
    private static $nodesTemplate;

    private static function loadTemplate(){
        $templateFilePath = app_path().
                DIRECTORY_SEPARATOR.
                $GLOBALS["AppConfig"]["appModelTemplatePath"].
                DIRECTORY_SEPARATOR.
                "AppModelTemplate.tpl";
        
        self::$template = file_get_contents($templateFilePath) ;

        $templateFilePath = app_path().
                DIRECTORY_SEPARATOR.
                $GLOBALS["AppConfig"]["appModelTemplatePath"].
                DIRECTORY_SEPARATOR.
                "AppModelNodesTemplate.tpl";
        
        $tpls = file_get_contents($templateFilePath) ;
        
        $tpls = explode("#section ",$tpls);
        
        self::$nodesTemplate = array();
        
        foreach($tpls as $tpl){
            if(starts_with($tpl, "hasMany")){
                self::$nodesTemplate["hasMany"] = substr($tpl,7);
            }
            else if(starts_with($tpl, "hasOne")){
                self::$nodesTemplate["hasOne"] = substr($tpl,6);
            }
            else if(starts_with($tpl, "belongsTo")){
                self::$nodesTemplate["belongsTo"] = substr($tpl,9);
            }
        }
        
    }
    
    private static function setTemplate($item, $value){
        self::$template = str_replace($item, $value , self::$template) ;
    }
    
    private static function writeToFile($model){
        $targetBase = app_path().DIRECTORY_SEPARATOR.$GLOBALS["AppConfig"]["appModelBasePath"];

        $targetBase = $targetBase.DIRECTORY_SEPARATOR. 
                str_replace("/", 
                        DIRECTORY_SEPARATOR , 
                        str_replace("\\", DIRECTORY_SEPARATOR , $model->getNameSpace()));
        
        if (!file_exists($targetBase)) {
            mkdir($targetBase, 0777, true);
        }
        $destFile = $targetBase.DIRECTORY_SEPARATOR.$model->name.".php";
        
        $handle = fopen($destFile, "w");
        fwrite($handle, self::$template);
        fclose($handle);
        
    }
    
    private static function createNodesRef($model){
        $str_hasOne = "";
        $str_hasMany = "";
        $str_belongsTo = "";
        foreach($model->nodes as $node){
            if(!$node->isMulti || $node->maxCount==1)
            {
                $tmp = str_replace('{nodeFullName}', $node->getFullName(), self::$nodesTemplate["hasOne"]);
                $tmp = str_replace('{nodeName}', $node->name, $tmp);
                $tmp = str_replace('{sonsMasterKey}', $node->masterIDField, $tmp);
                $str_hasOne = $str_hasOne.$tmp;
            }else{
                $tmp = str_replace('{nodeFullName}', $node->getFullName(), self::$nodesTemplate["hasMany"]);
                $tmp = str_replace('{nodeName}', $node->name, $tmp);
                $tmp = str_replace('{sonsMasterKey}', $node->masterIDField, $tmp);
                $str_hasMany = $str_hasMany.$tmp;
            }
        }
        self::setTemplate("#region hasMany", $str_hasMany);
        self::setTemplate("#region hasOne", $str_hasOne);
        if($model->masterNode)
        {
            $str_belongsTo = str_replace(
                    '{nodeName}', 
                    $model->masterNode->name, 
                    self::$nodesTemplate["belongsTo"]);
            $str_belongsTo = str_replace('{nodeFullName}', 
                            $model->masterNode->getFullName(), 
                            $str_belongsTo);
            $str_belongsTo = str_replace('{masterKey}', 
                            $model->masterIDField, 
                            $str_belongsTo);
            $str_belongsTo = str_replace('{mastersIDKey}', 
                            $model->masterNode->idField, 
                            $str_belongsTo);
        }
        self::setTemplate("#region belongsTo", $str_belongsTo);
    }

    public static function createModel(DM\DataNodeDescription $model) {
        
        self::loadTemplate();
        self::setTemplate('{table}', $model->getRealTableName());
        self::setTemplate('{primaryKey}', $model->idField);
        if ($model->masterNode) {
            self::setTemplate('{masterKey}', $model->masterIDField);
        } else {
            self::setTemplate('{masterKey}', "null");
        }
        self::setTemplate('{rootKey}', $model->getRootIDField());
        self::setTemplate('{fullName}', $model->getFullName());
        self::setTemplate('{nameSpace}', $model->getNameSpace());
        self::setTemplate('{name}', $model->name);
        self::createNodesRef($model);
        self::writeToFile($model);
        
        foreach($model->nodes as $node){
            self::createModel($node);
        }
    }


}
